/**
 */

package com.bei_en.common.util.SMS.ali;

import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bei_en.common.web.JsonSuccessResult;
import com.google.gson.Gson;
import com.taobao.api.ApiException;
import com.taobao.api.Constants;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumQueryRequest;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumQueryResponse;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

/**
 * @author Guocg
 *
 */
public class SMS {

	private static Logger log = LoggerFactory.getLogger(SMS.class);

	private static DefaultTaobaoClient client;
	static {
		client = new DefaultTaobaoClient(
				"http://gw.api.taobao.com/router/rest", "23458337",
				"009df07fb193dddf4fe62a536bf2a688", Constants.FORMAT_JSON,
				30000, 60000);
		client.setUseSimplifyJson(true);
	}

	/**
	 * 
	 * @author Guocg
	 * @param phoneNum
	 *            18600000000,13911111111
	 * @param code
	 * @return
	 */
	public static boolean sendVerifyCode(String phoneNum, String code) {

		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		// req.setExtend("sdf");
		req.setSmsType("normal");
		req.setSmsFreeSignName("身份验证");
		req.setSmsParamString("{\"code\":\"" + code
				+ "\",\"product\":\"\\\"叮咚e送\\\"\"} ");
		req.setRecNum(phoneNum);
		req.setSmsTemplateCode("SMS_8926381");
		req.setExtend(code);
		AlibabaAliqinFcSmsNumSendResponse rsp = new AlibabaAliqinFcSmsNumSendResponse();
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			e.printStackTrace();
		}
		String body = rsp.getBody();
		log.info(body);
		System.out.print(body);
		// {"result":{"err_code":"0","model":"100933817857^1101387036674","success":true},"request_id":"z29u1f41h9gm"}
		if (body.startsWith("{\"error")) {
			SmsRespFail resp = new Gson().fromJson(body, SmsRespFail.class);
			log.error(resp.getError_response().getMsg() + ":"
					+ resp.getError_response().getSub_msg());
			return false;
		}
		return true;
	}
	/**
	 * 
	 * @author Guocg
	 * @param phoneNum
	 *            18600000000,13911111111
	 * @param code
	 * @return
	 * @throws ApiException 
	 */
	public static JSONObject sendTakeCodeCodes(String phoneNum, String code,String name) throws ApiException {

		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		// req.setExtend("sdf");
		req.setSmsType("normal");
		req.setSmsFreeSignName("签收码");
		req.setSmsParamString("{\"code\":\"" + code
				+ "\",\"product\":\"\\\"" + name
				+ "\\\"\"} ");
		req.setRecNum(phoneNum);
		req.setSmsTemplateCode("SMS_10825376");
		req.setExtend(code);
		AlibabaAliqinFcSmsNumSendResponse rsp = new AlibabaAliqinFcSmsNumSendResponse();

			rsp = client.execute(req);
		
		String body = rsp.getBody();
		JSONObject js = JSONObject.fromObject(body);
		log.info(body);
		System.out.print(body);
		// {"result":{"err_code":"0","model":"100933817857^1101387036674","success":true},"request_id":"z29u1f41h9gm"}
		JSONObject ob = js.optJSONObject("result");
		if(ob==null){
			 ob = js.optJSONObject("error_response");
			 if(ob!=null){
				
			 }
			 return null;
		}
		if (ob.optInt("err_code") == 0) {
			JSONObject obs = new JSONObject();
			obs.put("BizId", ob.optString("model"));
			return obs;
		} else {
			return null;
		}
	}
	/**
	 * 
	 * @author Guocg
	 * @param phoneNum
	 *            18600000000,13911111111
	 * @param code
	 * @return
	 * @throws ApiException 
	 */
	public static JSONObject sendComplete(String phoneNum) throws ApiException {

		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		// req.setExtend("sdf");
		req.setSmsType("normal");
		req.setSmsFreeSignName("完成信息");
		req.setRecNum(phoneNum);
		req.setSmsTemplateCode("SMS_12210482");
	
		AlibabaAliqinFcSmsNumSendResponse rsp = new AlibabaAliqinFcSmsNumSendResponse();

			rsp = client.execute(req);
		
		String body = rsp.getBody();
		JSONObject js = JSONObject.fromObject(body);
		log.info(body);
		System.out.print(body);
		return null;
//		// {"result":{"err_code":"0","model":"100933817857^1101387036674","success":true},"request_id":"z29u1f41h9gm"}
//		JSONObject ob = js.optJSONObject("result");
//		if(ob==null){
//			 ob = js.optJSONObject("error_response");
//			 if(ob!=null){
//				
//			 }
//			 return null;
//		}
//		if (ob.optInt("err_code") == 0) {
//			JSONObject obs = new JSONObject();
//			obs.put("BizId", ob.optString("model"));
//			return obs;
//		} else {
//			return null;
//		}
	}
	/**
	 * 
	 * @author Guocg
	 * @param phoneNum
	 *            18600000000,13911111111
	 * @param code
	 * @return
	 * @throws ApiException 
	 */
	public static JSONObject sendCollectCodeCodes(String phoneNum, String code,String name) throws ApiException {

		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		// req.setExtend("sdf");
		req.setSmsType("normal");
		req.setSmsFreeSignName("取件码");
		req.setSmsParamString("{\"code\":\"" + code
				+ "\",\"product\":\"\\\"" + name
				+ "\\\"\"} ");
		req.setRecNum(phoneNum);
		req.setSmsTemplateCode("SMS_10885300");
		req.setExtend(code);
		AlibabaAliqinFcSmsNumSendResponse rsp = new AlibabaAliqinFcSmsNumSendResponse();
		rsp = client.execute(req);

		String body = rsp.getBody();
		JSONObject js = JSONObject.fromObject(body);
		log.info(body);
		System.out.println(body);
	//	{"error_response":{"code":15,"msg":"Remote service error","sub_code":"isv.BUSINESS_LIMIT_CONTROL","sub_msg":"触发业务流控","request_id":"qm3hv9c7iscn"}}
		// {"result":{"err_code":"0","model":"100933817857^1101387036674","success":true},"request_id":"z29u1f41h9gm"}
		JSONObject ob = js.optJSONObject("result");
		if(ob==null){
			 ob = js.optJSONObject("error_response");
			 if(ob!=null){
				
			 }
			 return null;
		}
		if (ob.optInt("err_code") == 0) {
			JSONObject obs = new JSONObject();
			obs.put("BizId", ob.optString("model"));
			return obs;
		} else {
			return null;
		}
	}
	/**
	 * 
	 * @author Guocg
	 * @param phoneNum
	 *            18600000000,13911111111
	 * @param code
	 * @return
	 * @throws ApiException 
	 */
	public static JSONObject sendVerifyCodes(String phoneNum, String code) throws ApiException {

		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		// req.setExtend("sdf");
		req.setSmsType("normal");
		req.setSmsFreeSignName("身份验证");
		req.setSmsParamString("{\"code\":\"" + code
				+ "\",\"product\":\"\\\"易考师\\\"\"} ");
		req.setRecNum(phoneNum);
		req.setSmsTemplateCode("SMS_14895766");
		req.setExtend(code);
		AlibabaAliqinFcSmsNumSendResponse rsp = new AlibabaAliqinFcSmsNumSendResponse();
		
			rsp = client.execute(req);
	
		String body = rsp.getBody();
		JSONObject js = JSONObject.fromObject(body);
		log.info(body);
		System.out.print(body);
		// {"result":{"err_code":"0","model":"100933817857^1101387036674","success":true},"request_id":"z29u1f41h9gm"}
		JSONObject ob = js.optJSONObject("result");
		if(ob==null){
			 ob = js.optJSONObject("error_response");
			 if(ob!=null){
				
			 }
			 return null;
		}
		if (ob.optInt("err_code") == 0) {
			JSONObject obs = new JSONObject();
			obs.put("BizId", ob.optString("model"));
			return obs;
		} else {
			return null;
		}
	}
	/**
	 * 
	 * @author Guocg
	 * @param phoneNum
	 *            18600000000,13911111111
	 * @param code
	 * @return
	 * @throws ApiException 
	 */
	public static JSONObject sendVerifyCodes(String phoneNum, String code,String str) throws ApiException {

		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		// req.setExtend("sdf");
		req.setSmsFreeSignName("身份验证");
		req.setSmsParamString("{\"code\":\"" + code
				+ "\",\"product\":\"\\\"易考师\\\"\"} ");
		req.setRecNum(phoneNum);
		req.setSmsTemplateCode("SMS_14895766");
		req.setExtend(code);
		AlibabaAliqinFcSmsNumSendResponse rsp = new AlibabaAliqinFcSmsNumSendResponse();
	
			rsp = client.execute(req);
	
		String body = rsp.getBody();
		JSONObject js = JSONObject.fromObject(body);
		log.info(body);
		System.out.print(body);
		// {"result":{"err_code":"0","model":"100933817857^1101387036674","success":true},"request_id":"z29u1f41h9gm"}
		JSONObject ob = js.optJSONObject("result");		
		if(ob==null){
			ob=new JSONObject();
			//{"error_response":{"code":15,"msg":"Remote service error","sub_code":"isv.SMS_TEMPLATE_ILLEGAL","sub_msg":"短信模板不合法","request_id":"iv1hc52nj2yu"}}

			switch (js.optJSONObject("error_response").optString("sub_code")){
	            case "isv.BUSINESS_LIMIT_CONTROL":
	            	ob.put("model", js.optString("sub_msg"));
	            	ob.put("status",1);
	                break;
	            case "isv.OUT_OF_SERVICE":
	            	ob.put("model", js.optString("sub_msg"));
	             	ob.put("status",1);
	                break;
	            case "isv.MOBILE_NUMBER_ILLEGAL":
	            	ob.put("model", js.optString("sub_msg"));
	            	ob.put("status",1);
	                break;
	            case "isv.QUERY_DATE_ILLEGAL":
	            	ob.put("model", js.optString("sub_msg"));
	            	ob.put("status",1);
	                break;
	            case "isv.INVALID_PARAMETERS":
	            	ob.put("model", js.optString("sub_msg"));
	            	ob.put("status",1);
	                break;
	            case "isv.ACCOUNT_NOT_EXISTS":
	            	ob.put("model", js.optString("sub_msg"));
	             	ob.put("status",1);
	                break;
	            case "isv.AMOUNT_NOT_ENOUGH":
	            	ob.put("model", js.optString("sub_msg"));
	            	ob.put("status",1);
	                break;
	            default :
	            	ob.put("model", js.optString("sub_msg"));
	            	ob.put("status",1);
	                break;
	        }
			 return ob;
		}
		if (ob.optInt("err_code") == 0) {
			JSONObject obs = new JSONObject();
			obs.put("BizId", ob.optString("model"));
			return obs;
		} else {
			return null;
		}
	}
	/**
	 * 检验验证码
	 * @author Guocg
	 * @param BizId
	 * @prama phone
	 * @param code
	 * @return
	 */
	public static boolean SelectVerifyCode(String BizId, String phone, int code) {

		AlibabaAliqinFcSmsNumQueryRequest req = new AlibabaAliqinFcSmsNumQueryRequest();
		req.setBizId(BizId);
		req.setRecNum(phone);
		req.setQueryDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
		req.setCurrentPage(1L);
		req.setPageSize(10L);
		AlibabaAliqinFcSmsNumQueryResponse rsp;
		try {
			rsp = client.execute(req);
			JSONObject js = JSONObject.fromObject(rsp.getBody());
			if(js.optJSONArray("values")!=null){
				if (js.optJSONArray("values").optJSONObject(0).optInt("extend") == code) {
					return true;
				} else {
					return false;
				}
			}else{
				JSONObject object=new JSONObject();
				switch (js.optString("sub_code")){
	            case "isv.BUSINESS_LIMIT_CONTROL":
	            	object.put("model", js.optString("sub_msg"));
	            	object.put("status",1);
	                break;
	            case"isv.OUT_OF_SERVICE":
	             	object.put("model", js.optString("sub_msg"));
	            	object.put("status",1);
	                break;
	            case "isv.MOBILE_NUMBER_ILLEGAL":
	             	object.put("model", js.optString("sub_msg"));
	            	object.put("status",1);
	                break;
	            case "isv.QUERY_DATE_ILLEGAL":
	             	object.put("model", js.optString("sub_msg"));
	            	object.put("status",1);
	                break;
	            case "isv.INVALID_PARAMETERS":
	             	object.put("model", js.optString("sub_msg"));
	            	object.put("status",1);
	                break;
	            case "isv.ACCOUNT_NOT_EXISTS":
	             	object.put("model", js.optString("sub_msg"));
	            	object.put("status",1);
	                break;
	            default :
	             	object.put("model", js.optString("sub_msg"));
	            	object.put("status",1);
	                break;
	        }
				return false;
			}
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}
}
